// import * as turf from '@turf/turf'

class CloudManager {
  /**
    * 构造函数
    * @param {Cesium.Viewer} viewer - 已初始化的Cesium Viewer实例
    * @param {Object} options - 配置选项
    * @param {string} [options.geojson] - GeoJSON数据地址
    * @param {number} [options.gridSize=0.02] - 网格密度（值越小云越密集）
    */
  constructor(viewer, options = {}) {
    if (typeof Cesium === 'undefined') {
      throw new Error('Cesium is not loaded. Please include Cesium.js before this script.');
    }

    // 验证viewer参数
    if (!(viewer instanceof Cesium.Viewer)) {
      throw new Error('First parameter must be a Cesium.Viewer instance');
    }

    // 默认配置
    this.defaults = {
      gridSize: 0.01,
      // 移除geojsonUrl，新增geoJsonData支持外部传入数据
      geoJsonData: null
    };

    // 合并配置
    this.config = { ...this.defaults, ...options };

    // 保存viewer实例
    this.viewer = viewer;

    // 从配置中获取参数
    this.geoJsonData = this.config.geoJsonData; // 外部传入的GeoJSON数据
    this.gridSize = this.config.gridSize;

    // 云相关属性
    this.clouds = null;
    this.cloudInstances = []; // 存储多个云实例
    // DOM元素引用
    this.scaleX = null;
    this.scaleY = null;
    this.scaleXValue = null;
    this.scaleYValue = null;
    this.brightness = null;
    this.brightnessValue = null;

    // 初始化流程
    // this.initViewerSettings();
    this.generateCloudsFromGeoJSON(this.geoJsonData);
    // this.bindElements();
    // this.bindEvents();
  }



  // 初始化视图设置
  initViewerSettings() {
    this.viewer.scene.debugShowFramesPerSecond = true;
    this.viewer.scene.globe.depthTestAgainstTerrain = true;
  }








  /**
   * 从外部传入的GeoJSON数据生成云
   * @param {Object} geoJson - 外部处理好的GeoJSON数据对象
   */
  generateCloudsFromGeoJSON(geoJson) {
    if (!geoJson || !geoJson.features || geoJson.features.length === 0) {
      console.warn('Invalid GeoJSON data provided, using default area instead');
      this.useDefaultArea();
      return;
    }

    // 取第一个多边形要素
    const feature = geoJson.features[0];
    if (feature.geometry.type !== 'Polygon') {
      console.warn('GeoJSON feature is not a Polygon, using default area');
      this.useDefaultArea();
      return;
    }

    // 获取多边形坐标
    const coordinates = feature.geometry.coordinates[0] || feature.geometry.coordinates;

    this.generateCloudsInPolygon(coordinates);
    this.setCameraToPolygon(coordinates);
  }



  // 使用默认多边形区域
  useDefaultArea() {
    const defaultPolygon = [
      [114.35, 30.50, 200],
      [114.45, 30.50, 200],
      [114.45, 30.55, 200],
      [114.35, 30.55, 200],
      [114.35, 30.50, 200]
    ];
    this.generateCloudsInPolygon(defaultPolygon);
    this.setCameraToPolygon(defaultPolygon);
  }

  // 在多边形范围内生成网格状分布的云
  generateCloudsInPolygon(polygonCoordinates) {
    // 初始化云集合
    this.clouds = this.viewer.scene.primitives.add(
      new Cesium.CloudCollection({
        noiseDetail: 16.0,
      })
    );

    // 计算多边形边界范围
    const bounds = this.calculatePolygonBounds(polygonCoordinates);

    if (!bounds) return;

    // 生成网格点并在多边形内创建云
    for (let lon = bounds.minLon; lon <= bounds.maxLon; lon += this.gridSize) {
      for (let lat = bounds.minLat; lat <= bounds.maxLat; lat += this.gridSize) {
        // 检查点是否在多边形内
        if (this.isPointInPolygon([lon, lat], polygonCoordinates)) {
          // 随机高度偏移（180-220之间）
          const height = (polygonCoordinates[0][2] || 200) + (Math.random() * 40 - 20);
          // 随机尺寸偏移（±10%）
          const scaleX = 1437 * (0.9 + Math.random() * 0.2);
          const scaleY = 500 * (0.9 + Math.random() * 0.2);

          // 创建云实例
          const cloud = this.clouds.add({
            position: new Cesium.Cartesian3.fromDegrees(lon, lat, height),
            scale: new Cesium.Cartesian2(scaleX, scaleY),
            slice: 0.36 + (Math.random() * 0.1 - 0.05), // 微小随机变化
            brightness: 1,
            color: Cesium.Color.YELLOW // 添加颜色属性
          });
          this.cloudInstances.push(cloud);
        }
      }
    }

    // 初始化尺寸显示
    this.changeScale();
  }

  // 计算多边形边界范围
  calculatePolygonBounds(coordinates) {
    if (!coordinates || coordinates.length < 3) return null;

    let minLon = Infinity, maxLon = -Infinity;
    let minLat = Infinity, maxLat = -Infinity;

    coordinates.forEach(point => {
      const lon = point[0];
      const lat = point[1];
      minLon = Math.min(minLon, lon);
      maxLon = Math.max(maxLon, lon);
      minLat = Math.min(minLat, lat);
      maxLat = Math.max(maxLat, lat);
    });

    return { minLon, maxLon, minLat, maxLat };
  }

  // 判断点是否在多边形内（射线法）
  isPointInPolygon(point, polygon) {
    const x = point[0], y = point[1];
    let inside = false;

    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
      const xi = polygon[i][0], yi = polygon[i][1];
      const xj = polygon[j][0], yj = polygon[j][1];

      const intersect = ((yi > y) !== (yj > y))
        && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }

    return inside;
  }

  /**
   * 设置相机看向多边形区域
   * @param {Array} polygonCoordinates - 多边形坐标数组
   */
  setCameraToPolygon(polygonCoordinates) {
    const bounds = this.calculatePolygonBounds(polygonCoordinates);
    if (!bounds) {
      this.setDefaultCameraPosition();
      return;
    }

    const centerLon = (bounds.minLon + bounds.maxLon) / 2;
    const centerLat = (bounds.minLat + bounds.maxLat) / 2;
    const height = (polygonCoordinates[0][2] || 200) + 500;

    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, height),
      duration: 2,
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-45), // 修复错误的new关键字
        roll: 0.0
      }
    });
  }

  // 设置默认相机位置
  setDefaultCameraPosition() {
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(114.401867, 30.520423, 1000),
      duration: 2,
      orientation: {
        heading: Cesium.Math.toRadians(281.8),
        pitch: Cesium.Math.toRadians(-30), // 修复错误的new关键字
        roll: 0.0
      }
    });
  }

  // 绑定DOM元素
  bindElements() {
    this.scaleX = document.getElementById('ScaleX');
    this.scaleXValue = document.getElementById('ScaleXValue');
    this.scaleY = document.getElementById('ScaleY');
    this.scaleYValue = document.getElementById('ScaleYValue');
    this.brightness = document.getElementById('Brightness');
    this.brightnessValue = document.getElementById('BrightnessValue');
  }

  // 绑定事件监听
  bindEvents() {
    // 为DOM元素绑定事件（替代全局函数）
    if (this.scaleX) {
      this.scaleX.addEventListener('input', () => this.changeScale());
    }
    if (this.scaleXValue) {
      this.scaleXValue.addEventListener('change', () => this.changeScaleX());
    }
    if (this.scaleY) {
      this.scaleY.addEventListener('input', () => this.changeScale());
    }
    if (this.scaleYValue) {
      this.scaleYValue.addEventListener('change', () => this.changeScaleY());
    }
    if (this.brightness) {
      this.brightness.addEventListener('input', () => this.changeBrightness());
    }
    if (this.brightnessValue) {
      this.brightnessValue.addEventListener('change', () => this.changeBrightnessValue());
    }
  }

  // 改变所有云的尺寸
  changeScale() {
    const sX = Number(this.scaleX?.value || 1437);
    const sY = Number(this.scaleY?.value || 500);

    if (this.scaleXValue) this.scaleXValue.value = sX;
    if (this.scaleYValue) this.scaleYValue.value = sY;

    this.cloudInstances.forEach(cloud => {
      cloud.scale = new Cesium.Cartesian2(sX, sY);
    });
  }

  // 通过文本框改变X轴尺寸
  changeScaleX() {
    if (this.scaleX && this.scaleXValue) {
      this.scaleX.value = Number(this.scaleXValue.value);
      this.changeScale();
    }
  }

  // 通过文本框改变Y轴尺寸
  changeScaleY() {
    if (this.scaleY && this.scaleYValue) {
      this.scaleY.value = Number(this.scaleYValue.value);
      this.changeScale();
    }
  }

  // 改变所有云的亮度
  changeBrightness() {
    const brightness = Number(this.brightness?.value || 1);
    if (this.brightnessValue) this.brightnessValue.value = brightness;

    this.cloudInstances.forEach(cloud => {
      cloud.brightness = brightness;
    });
  }

  // 通过文本框改变亮度
  changeBrightnessValue() {
    if (this.brightness && this.brightnessValue) {
      this.brightness.value = Number(this.brightnessValue.value);
      this.changeBrightness();
    }
  }

  // 提供获取viewer的方法
  getViewer() {
    return this.viewer;
  }
}

// 导出模块
if (typeof module !== 'undefined' && module.exports) {
  module.exports = CloudManager;
} else if (typeof window !== 'undefined') {
  window.CloudManager = CloudManager;
}

export default CloudManager;